export default class PoolDB {
  pool = []
  dbSavedTimestamps = []

  constructor({ adaptor }) {
    this.db = new adaptor()

    setInterval(async () => {
      try {
        if (this.pool.length === 0) return

        // truely save
        await this.db.insertMany(this.pool)

        this.dbSavedTimestamps.push(
          ...Array.from(new Set(this.pool.map(item => item.timestamp)))
        )

        this.pool.length = 0
      } catch (e) {
        console.error(e)
      }
    }, 3000)
  }

  init() {
    this.db.init()
  }

  async query(timestamp) {
    const matchItem = this.pool.find(item => item.timestamp === timestamp)
    if (matchItem) {
      return matchItem
    }

    if (this.dbSavedTimestamps.includes(timestamp)) {
      return this.db.query({ timestamp })
    }
  }

  async insert(timestamp, data) {
    // find it at pool
    if (this.pool.find(item => item.timestamp === timestamp)) {
      return
    }

    if (this.dbSavedTimestamps.includes(timestamp)) return

    this.pool.push({
      timestamp,
      data
    })
  }

  getAll() {
    return this.db.chart.toArray()
  }
}
